package com.itlong.cloud.wechat.service.impl;

import com.itlong.cloud.POJO.DTO.common.AccessToken;
import com.itlong.cloud.POJO.DTO.common.ResponseTextMessage;
import com.itlong.cloud.POJO.PO.WeChatUserOpenIdInfoPO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.WeChatPushedType;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.AccessTokenUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import com.itlong.cloud.utils.words.WechatMessageUtil;
import com.itlong.cloud.wechat.dao.IWeChatDao;
import com.itlong.cloud.wechat.service.IWeChatMessageService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 微信消息处理service
 *
 * @createDate 2019/05/17
 */
@Service
@RefreshScope
public class WechatMessageServiceImpl implements IWeChatMessageService{
    protected static final Logger LOG = LoggerFactory.getLogger(WechatMessageServiceImpl.class);

    @Autowired
    RedisService redisService;

    @Autowired
    IWeChatDao iWeChatDao;

    @Value("${" + PlatformConstants.WECHAT_OFFICIAL_APPID + "}")
    private String appid;
    @Value("${" + PlatformConstants.WECHAT_OFFICIAL_SECRET + "}")
    private String appsecret;
     /**
     * <desc>
     *      处理微信发来的请求返回推送xml
     * </desc>
     *
     * @param requestMap
     * @return
     *@createDate 2019/05/17
     */
    public String processRequestForNews(Map<String, String> requestMap){
        String respMessage="";
        ResponseTextMessage textMessage=new ResponseTextMessage();
        textMessage.setCreateTime(new Date().getTime()/1000);
        try{
            // 发送方帐号（open_id）
            String fromUserName = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            // 文本消息内容
            String content=requestMap.get("Content");
            //MsgId
            String msgId=requestMap.get("MsgId");
            //事件类型
            String event=requestMap.get("Event");
            //时间key值
            String eventKey=requestMap.get("EventKey");
            textMessage.setToUserName(fromUserName);
            textMessage.setFromUserName(toUserName);
            textMessage.setMsgType(WechatMessageUtil.RESP_MESSAGE_TYPE_TEXT);
           if(msgType.equals(WechatMessageUtil.REQ_MESSAGE_TYPE_EVENT)){
                //推送消息类型
                if(event!=null&&event.equals(WeChatPushedType.SUBSCRIBE.getDescription())){
                    //根据发送方openId 查询 unionId
                    String url = "https://api.weixin.qq.com/cgi-bin/user/info";
                    Map<String,String> params = new HashMap<>();
                    params.put("access_token",redisService.get(RedisConstant.WECHAT_OFFICIAL_ACCESS_TOKEN));
                    params.put("openid",fromUserName);
                    params.put("lang","zh_CN");
                    String result = HttpProtocolUtil.httpGet(url,params);
                    Map<String,Object> wxResult = JsonUtil.toObject(result,HashMap.class);
                    String unionId = wxResult.get("unionid") != null ? wxResult.get("unionid").toString() : null;
                    String wxOpenId = wxResult.get("openid").toString();
                    String nickName = StringHandlerUtil.filterEmoji(wxResult.get("nickname").toString());
                    //入库
                    if(unionId!=null){
                        //检测unionid是否存在
                        String userOpenId = iWeChatDao.checkUnionIdIsExists(unionId);
                        if(StringUtils.isNotBlank(userOpenId)){
                            //更新已有数据的wxOpenId
                            iWeChatDao.updateWxOpenId(userOpenId,wxOpenId,nickName);
                        }else{
                            WeChatUserOpenIdInfoPO infoPO = new WeChatUserOpenIdInfoPO();
                            infoPO.setUserOpenId(LogicIdUtil.bussinessId());
                            infoPO.setUnionId(unionId);
                            infoPO.setOfficialNickName(nickName);
                            infoPO.setOfficialOpenId(wxOpenId);
                            infoPO.setCreateTime(new Date());
                            infoPO.setStatus(DataStatusEnum.NORMAL.getType());
                            iWeChatDao.save(SqlUtil.durableData(infoPO,PlatformConstants.TABLE_SAVE));
                        }
                    }
                    textMessage.setContent("你好，欢迎关注云半径！");
                    respMessage= WechatMessageUtil.textMessageToXml(textMessage);
                }
            }
            LOG.info("【微信消息处理成功】，当前时间：" + DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss")) ;
        }catch (Exception e){
//            LOG.error("【微信消息处理异常】，当前时间：" + DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss"));
            e.printStackTrace();
        }
        return respMessage;
    }

    /**
     * <desc>
     *      定时任务更新微信公众号与小程序之间的关联关系
     * </desc>
     *
     * @throws Exception
     * @author Jiaqi.X
     * @createDate 2019/05/21
     */
    public void bindOfficeOpenIdAndMiniProgramOpenId() throws Exception {
        String accessToken=redisService.get(RedisConstant.WECHAT_OFFICIAL_ACCESS_TOKEN);
        if (accessToken == null) {
            //如果没有获得accessToken 那么创建一个accessToken
            AccessToken token = AccessTokenUtil.getAccessToken(appid, appsecret);
            redisService.set(RedisConstant.WECHAT_OFFICIAL_ACCESS_TOKEN, RedisConstant.WECHAT_ACCESS_TOKEN_TOKEN_TIME,token.getAccess_token());
            accessToken = token.getAccess_token();
            LOG.info("【accessToken】："+accessToken);
        }
        //根据发送方openId 查询 unionId
        String url = "https://api.weixin.qq.com/cgi-bin/user/get";
        Map<String,String> params = new HashMap<>();
        params.put("access_token",accessToken);
        String result = HttpProtocolUtil.httpGet(url,params);
        Map<String,Object> wxResult = JsonUtil.toObject(result,HashMap.class);
        if(wxResult.get("data")!=null){
            List<String> openIds = (ArrayList)((HashMap)wxResult.get("data")).get("openid");
            List<String> openIdsExist = iWeChatDao.getExistsOpenIds();
            //去除当前已存在于数据库的officeOpenId
            lv1:for(int i = openIds.size() - 1 ;i >= 0 ; i--){
                lv2:for(String openId : openIdsExist){
                    if(openIds.get(i).equals(openId)){
                        openIds.remove(i);
                    }
                    break lv2;
                }
            }
            for(String openId : openIds){
                //根据发送方openId 查询 unionId
                String infoUrl = "https://api.weixin.qq.com/cgi-bin/user/info";
                Map<String,String> selectParams = new HashMap<>();
                selectParams.put("access_token",accessToken);
                selectParams.put("openid",openId);
                selectParams.put("lang","zh_CN");
                String selectResult = HttpProtocolUtil.httpGet(infoUrl,selectParams);
                Map<String,Object> officeResult = JsonUtil.toObject(selectResult,HashMap.class);
                //LOG.info("【更新微信公众号与小程序之间的关联关系】："+JsonUtil.toJSON(officeResult));
                String unionId = officeResult.get("unionid") != null ? officeResult.get("unionid").toString() : null;
                if(StringUtils.isBlank(unionId)){
                    continue;
                }
                String wxOpenId = officeResult.get("openid").toString();
                String nickName = StringHandlerUtil.filterEmoji(officeResult.get("nickname").toString());
                //入库
                if(unionId!=null){
                    //检测unionid是否存在
                    String userOpenId = iWeChatDao.checkUnionIdIsExists(unionId);
                    if(StringUtils.isNotBlank(userOpenId)){
                        //更新已有数据的wxOpenId
                        iWeChatDao.updateWxOpenId(userOpenId,wxOpenId,nickName);
                    }else{
                        WeChatUserOpenIdInfoPO infoPO = new WeChatUserOpenIdInfoPO();
                        infoPO.setUserOpenId(LogicIdUtil.bussinessId());
                        infoPO.setOfficialOpenId(wxOpenId);
                        infoPO.setUnionId(unionId);
                        infoPO.setCreateTime(new Date());
                        infoPO.setOfficialNickName(nickName);
                        infoPO.setStatus(DataStatusEnum.NORMAL.getType());
                        iWeChatDao.save(SqlUtil.durableData(infoPO,PlatformConstants.TABLE_SAVE));
                    }
                }
             }
        }
    }


//    public static void main(String[] args) throws Exception {
//        String token = "27_N5vyzoMcTOvAPkViJnVYWmkuWKTDChN5lvFKhJ0LY3jl9uPI46Xk6rnXXJ8qDVqIM_8GEWdijk3fI1ZXyHmtCtj7NajaqFNM6k-V2UcsptXkLFGC7TfW1cWC5CzjK741HoclRxT8B8lmZQ8vRYCjACAWDH";
//        String url = "https://api.weixin.qq.com/cgi-bin/user/get";
//        Map<String,String> params = new HashMap<>();
//        params.put("access_token",token);
//        String result = HttpProtocolUtil.httpGet(url,params);
//        Map<String,Object> wxResult = JsonUtil.toObject(result,HashMap.class);
//        System.out.println(wxResult.get("openId"));
//    }
}
